#!/usr/bin/env python
# encoding: utf-8
"""
weatherparser.py

Writes the weather code and temperature to a file in fixed time intervals.
This program runs infinitely and can be stopped by a keyboard interrupt off
the command line (Ctrl-D).

Weather data from Yahoo RSS weather feed.
Weather code chart can be found at http://developer.yahoo.com/weather/#codes

Created by Jian Wei Gan on 2009-11-10.
Copyright (c) 2009 __MyCompanyName__. All rights reserved.
"""

from BeautifulSoup import BeautifulStoneSoup
import sys
import os
import time
import urllib2

DURHAM_ZIP = 27708
WRITE_TO = "weather/weather_test.txt"
DELIMITER = '\n'
TEN_MIN_IN_SECS = 600

def get_request():
    request = urllib2.Request("http://weather.yahooapis.com/forecastrss?p=%d" %
                              DURHAM_ZIP)
    request.add_header('User-Agent', 'DukeWeatherParser/1.0')
    return request

def get_data(request):
    opener = urllib2.build_opener()
    rss_data = opener.open(request)
    rss_str = rss_data.read()
    rss_data.close()
    
    soup = BeautifulStoneSoup(rss_str)
    yweather = soup.find('yweather:condition')
    weather_code = yweather['code']
    temp = yweather['temp'] # Temp in Farenheit
    return (weather_code, temp)

def write_data(filename, weather_code, temp):
    output_file = open(filename, 'w')
    output_file.write("%s%s%s" % (weather_code, DELIMITER, temp))
    output_file.close()

if __name__ == '__main__':
    request = get_request()
    while True:
        weather_code, temp = get_data(request)
        write_data(WRITE_TO, weather_code, temp)
        print "wrote code: %s, temp: %s" % (weather_code, temp)
        time.sleep(TEN_MIN_IN_SECS)
    